//
//  MusicInfoHandle.m
//  MusicPlayer
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 韩宏. All rights reserved.
//

#import "MusicInfoHandle.h"
#import "MusicInfo.h"

@interface MusicInfoHandle ()

@property (nonatomic, strong) NSMutableArray *musicInfoArray;

@end

static MusicInfoHandle *musicInfoHandle = nil;

@implementation MusicInfoHandle

+ (MusicInfoHandle *)shareHandle {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (musicInfoHandle == nil) {
            musicInfoHandle = [[MusicInfoHandle alloc] init];
        }
    });
    return musicInfoHandle;
}

//获取音乐信息
- (void)getMusicInfosWithUrl:(NSString *)urlString completion:(void(^)(NSArray *musicInfo, NSError *error))completion
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            MusicInfo *musicInfo = nil;
            NSError *resultError = error;
            if (!resultError) {
                //生成plit文件路径
                NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"result.plist"];
                //将请求的数据写入本地
                [data writeToFile:filePath options:NSDataWritingAtomic error:&resultError];
                //判断数据写入文件是否成功
                if (!resultError) {
                    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
                    //清空属性数组的中的所有值,重新加载数据
                    [self.musicInfoArray removeAllObjects];
                    for (NSDictionary *dict in array) {
                        //讲数组中的数据生成model
                        musicInfo = [MusicInfo new];
                        [musicInfo setValuesForKeysWithDictionary:dict];
                        [self.musicInfoArray addObject:musicInfo];
                    }
                } else {
                    resultError = [NSError errorWithDomain:@"数据写入文件失败" code:0 userInfo:@{@"resultType" : @"MusicInfoGet"}];
                }
                
            } else {
                resultError = [NSError errorWithDomain:@"请求数据失败" code:1 userInfo:@{@"resultType" : @"MusicInfoGet"}];
            }
            //实现回调
            if (completion) {
                completion(_musicInfoArray, resultError);
            }
        });
    }];
    [task resume];
}

- (NSMutableArray *)musicInfoArray
{
    if (!_musicInfoArray) {
        _musicInfoArray = [[NSMutableArray alloc] init];
    }
    return _musicInfoArray;
}

- (NSInteger)numberOfRowsInSection:(NSInteger)sectio
{
    return _musicInfoArray.count;
}

- (MusicInfo *)musicCellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _musicInfoArray[indexPath.row];
}

//根据索引获取上一首歌曲
- (MusicInfo *)musicInfoLastWithIndex:(NSInteger *)index
{
    if (*index == 0) {
        *index = _musicInfoArray.count - 1;
        return [_musicInfoArray lastObject];
    } else {
        *index = *index - 1;
        return [_musicInfoArray objectAtIndex:*index];
    }
}

//根据索引获取下一首歌曲
- (MusicInfo *)musicInfoNextWithIndex:(NSInteger *)index
{
    if (*index == _musicInfoArray.count - 1) {
        *index = 0;
        return [_musicInfoArray firstObject];
    } else {
        *index = *index + 1;
        return [_musicInfoArray objectAtIndex:*index];
    }
}

//随机获取歌曲
- (MusicInfo *)musicInfoRandomWithIndex:(NSInteger *)index
{
    *index = arc4random() % _musicInfoArray.count;
    return _musicInfoArray[*index];
}

@end
